//
//  MyLayout.m
//  MMLOOK
//
//  Created by dllo on 15/9/28.
//  Copyright © 2015年 武俊娥. All rights reserved.
//

#import "MyLayout.h"
#import "WedModel.h"

#define RealWidth ([UIScreen mainScreen].bounds.size.width - 45) / 2

@interface MyLayout ()

@property(nonatomic, assign)CGFloat height;

@end

@implementation MyLayout


-(void)dealloc
{
    [_modelArr release];
    [_array release];
    [super dealloc];
    

}

-(instancetype)init
{
    self = [super init];
    if (self) {
        
        self.array = [NSMutableArray array];
        
        self.modelArr = [NSMutableArray array];
        
    }
    
    return self;
}



//提供每个item的布局准备工作

-(void)prepareLayout
{
    [super prepareLayout];
    
    [self calculatorHeight];
}


-(void)calculatorHeight
{
    
    self.array = [NSMutableArray array];
    
    NSInteger itemNum = [self.collectionView numberOfItemsInSection:0];
    
    
    CGFloat offLeft = 0;
    
    CGFloat offRight = 0;
    
    
    for (int i = 0; i < itemNum; i++) {
        
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        
        WedModel *model = [self.modelArr objectAtIndex:i];
        
        CGFloat realHeight = ([model.height floatValue] * RealWidth / [model.width floatValue]) + 20;
        
        if (i % 2 ==0) {
            
            att.frame = CGRectMake(15, offLeft, RealWidth, realHeight );
            
            offLeft = offLeft + realHeight + 15;
            
            
        } else {
            
            att.frame = CGRectMake(RealWidth + 30, offRight, RealWidth, realHeight );
            
            offRight = realHeight + offRight + 15;
            
        }
        
        self.height = offLeft > offRight ? offLeft : offRight ;
        
        [self.array addObject:att];
    }
    
}

//返回一个滚动的范围
-(CGSize)collectionViewContentSize
{
    
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, self.height);
    
}



-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    
    
    NSMutableArray *currentArr = [NSMutableArray array];
    
    for (UICollectionViewLayoutAttributes *att in self.array) {
        
        if (CGRectIntersectsRect(att.frame, rect) || CGRectContainsRect(att.frame, rect)) {
            
            [currentArr addObject:att];
            
        }
        
    }
    
    return currentArr;
    
}


-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.array objectAtIndex:indexPath.item];
}




@end
